package org.xurui.sxl.protocol.command.impl;

import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.event.EventMessage;
import org.springframework.util.StringUtils;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据补传
 */
public class CmdCodec_V3 implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.V3.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return false;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //数据补传 设备上报 TODO 没有 SV,BAT
        //格式：*XX,YYYYYYYYYYYYYYY,V3,HHMMSS,posnum,firsttime,firstDate,latitude1,longitude1,latitude2,longitude2,latitude3,longitude3,latitude4,longitude4,latitude5,longitude5,DDMMYY,tracker_status#
        //例子：*TJ,866104040001458,V3,130325,2,130305,220912,2212.8745,11346.6574,2212.8746,11346.6577,220912,FFFFFFFF#
        //回复格式：*XX,YYYYYYYYYYYYYYY,V4,V3,seq,HHMMSS#
        //回复示例：*TJ,866104040001458,V4,V3,130325,130326#
        //参数说明：posnum 轨迹点的数量
        //参数说明：firsttime 定位轨迹点集合中第一个点的时间，格式同 HHMMSS
        //参数说明：Firstdate 定位轨迹点集合中第一个点的日期，格式同 DDMMYY
        //参数说明：坐标 latitude1,longitude1，第一个点的经纬度。latitude2,longitude2,第二个点…
        //解析数据为事件上报
        EventMessage eventMessage = new EventMessage();
        //ReportPropertyMessage report = ReportPropertyMessage.create();
        String[] payloadArr = payload.replaceAll("\\*", "").split(",");
        String deviceId = payloadArr[1];
        eventMessage.setEvent(CommandEnum.V3.name());
        eventMessage.setDeviceId(deviceId);
        eventMessage.setMessageId(deviceId + "_" + payloadArr[3]);
        eventMessage.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        properties.put("uptime",payloadArr[3]);
        //properties.put("posnum", NumberUtils.parseInt(payloadArr[4]));
        properties.put("firsttime",payloadArr[5]);
        properties.put("firstDate",payloadArr[6]);
        String[] paraArr= Arrays.copyOfRange(payloadArr,6,payloadArr.length-2);
        String para="";
        int num=1;
        for (int i=1;i<paraArr.length;i++){
            // System.out.println(paraArr[i]);
            if(i%2==0){
                if(!StringUtils.isEmpty(BinaryUtils.getWgs84LonLat(paraArr[i],"lon"))){
                    properties.put("longitude"+num,BinaryUtils.getWgs84LonLat(paraArr[i],"lon"));
                    num=num+1;
                }

            }else{
                if(!StringUtils.isEmpty(BinaryUtils.getWgs84LonLat(paraArr[i],"lat"))) {
                    properties.put("latitude" + num, BinaryUtils.getWgs84LonLat(paraArr[i], "lat"));
                }
            }
        }
        properties.put("posnum", num);
        int j=6+paraArr.length;
        properties.put("upday",payloadArr[j]);
        String trackerStatusHex = payloadArr[j+1];

        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        //report.setProperties(properties);
        eventMessage.setData(properties);
        //回复设备数据
        //TODO 暂时没找到设备回复消息的方法
        /*String time = DateFormatUtils.format(new Date(),"HHmmss");
        String reply="*"+payloadArr[0]+","+deviceId+",V4,"+CommandEnum.V3.name()+","+payloadArr[3]+","+time+"#";
        context.getSession()
            .send(EncodedMessage
                .simple(Unpooled.wrappedBuffer(reply.getBytes())))
            .subscribe();*/
        SxlMessageUtils.bulidAndSend2DeviceV4Msg(context,payloadArr[0],deviceId,CommandEnum.V3.name(),payloadArr[3]);
        //return genDeviceMessage(report);
        return genDeviceMessage(eventMessage);
    }
}
